package com.topisv.tms.task.dispatch;

import java.util.concurrent.BlockingQueue;

import javax.persistence.OptimisticLockException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.OptimisticLockingFailureException;

import com.topisv.tms.entity.task.DispatchOrderTask;
import com.topisv.tms.service.task.DispatchOrderTaskService;
import com.topisv.tms.utils.enums.TaskStatus;

public class DispatchOrderTaskWorker extends Thread {
	private Logger logger = LoggerFactory.getLogger(getClass());
	private BlockingQueue<DispatchOrderTask> tasks;
	private DispatchOrderTaskService service;

	public DispatchOrderTaskWorker(BlockingQueue<DispatchOrderTask> tasks, DispatchOrderTaskService service) {
		this.tasks = tasks;
		this.service = service;
	}

	@Override
	public void run() {
		while (true) {
			DispatchOrderTask task = null;
			try {
				task = tasks.take();
				if (task != null) {
					service.dealData(task);
				}
			} catch (Exception e) {
				if(!(e.getCause() instanceof OptimisticLockException) && !(e instanceof OptimisticLockingFailureException)){
					logger.error(new StringBuilder("[").append(task != null ? task.getOrderNo() : null).append("]").append(" case some error.").toString(), e);
				}
				if (task != null) {
					if (task.getDealCount() >= 5) {
						task.setDealStatus(TaskStatus.FAIL.getStatus());
					} else {
						if(!(e.getCause() instanceof OptimisticLockException) && !(e instanceof OptimisticLockingFailureException)){
							task.setDealCount(task.getDealCount() + 1);
						}
						task.setDealStatus(TaskStatus.UNHAND.getStatus());
						task.setDealIp(null);
					}
					service.saveData(task);
				}
			}
		}
	}

}
